package com.example.combwyaq.visualinterface.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.combwyaq.R;
import com.example.combwyaq.db.DaoManager;
import com.example.combwyaq.db.UserEntityDao;
import com.example.combwyaq.entity.UserEntity;
import com.example.combwyaq.http.Api;
import com.example.combwyaq.http.HttpFactory;
import com.example.combwyaq.http.HttpType;
import com.example.combwyaq.mvp.contract.PersonalDetailsConteract;
import com.example.combwyaq.mvp.di.DaggerPersonalDetailsComponent;
import com.example.combwyaq.mvp.di.PersonalDetailsModules;
import com.example.combwyaq.mvp.model.PersonalDetailsModel;
import com.example.combwyaq.mvp.model.entity.BaseEntity;
import com.example.combwyaq.mvp.presenter.PersonalDetailsPresenter;
import com.example.combwyaq.mvp.viwe.BaseActivity;
import com.example.combwyaq.utils.GlideUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class PersonalDetailsActivity extends BaseActivity<PersonalDetailsPresenter>
        implements PersonalDetailsConteract.IPersonalView, View.OnClickListener {

    private RelativeLayout rlImg;
    private ImageView detailHeadImg;
    private RelativeLayout rlName;
    private TextView detailName;
    private RelativeLayout rlSex;
    private TextView detailSex;
    private RelativeLayout detailBackParent;
    private View detailBackgroundBack;
    private TextView detailCamera;
    private TextView detailOpenPhoto;
    private TextView detailCancel;
    private String path;
    private View inflate;
    private TextView editNick;
    private RelativeLayout detailBackParent2;
    private TextView detailPrivary;
    private TextView detailMan;
    private TextView detailWomen;
    private TextView detailCancel2;
    private int user_id;
    private PopupWindow pop;
    private PersonalDetailsPresenter mPresenter;
    private ImageView goBack;
    private String thipath;
    private FrameLayout activityPersonalDetailsLl;
    private ImageView modifyTheName;
     private static final String TAG = "PersonalDetailsActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_details);
        initView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.VIBRATE,
                    Manifest.permission.WAKE_LOCK
            }, 101);
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        /*修改状态栏当中的图片以及文字颜色*/
        BarUtils.setStatusBarColor(this,Color.WHITE);
        /*添加让出装状态栏高度->防止contenView布局绘制到状态栏上*/
        BarUtils.addMarginTopEqualStatusBarHeight(addStatusView());

    }

    @Override
    protected int addBarColor() {
        return Color.WHITE;
    }

    @Override
    public View addStatusView() {
        return f(R.id.activity_personal_details_ll);
    }

    @Override
    public void refreshView(BaseEntity entity) {
        Toast.makeText(this, ""+entity.message, Toast.LENGTH_SHORT).show();
    }


    @Override
    public int bindLayout() {
        return R.layout.activity_personal_details;
    }

    public void initView() {
//        inflate_parent = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_detail, null);
        inflate = LayoutInflater.from(getApplicationContext()).inflate(R.layout.view_detail_pop, null);
        editNick = inflate.findViewById(R.id.edit_nickname);
        goBack = (ImageView) findViewById(R.id.go_back1);
        goBack.setOnClickListener(this::onClick);
        rlImg = findViewById(R.id.rl_img);
        rlImg.setOnClickListener(this::onClick);
        detailHeadImg = findViewById(R.id.detail_head_img);
        rlName = findViewById(R.id.rl_name);
        rlName.setOnClickListener(this::onClick);
        modifyTheName = (ImageView) findViewById(R.id.modify_the_name);
        modifyTheName.setOnClickListener(this::onClick);
        detailName = findViewById(R.id.detail_name);
        rlSex = findViewById(R.id.rl_sex);
        rlSex.setOnClickListener(this::onClick);
        detailSex = findViewById(R.id.detail_sex);
        detailBackParent = findViewById(R.id.detail_back_parent);
        detailBackgroundBack = findViewById(R.id.detail_background_back);
        detailCamera = findViewById(R.id.detail_camera);
        detailOpenPhoto = findViewById(R.id.detail_open_photo);
        detailCancel = findViewById(R.id.detail_cancel);
        detailCamera.setOnClickListener(this::onClick);
        detailOpenPhoto.setOnClickListener(this::onClick);
        detailCancel.setOnClickListener(this::onClick);
        detailBackParent2 = findViewById(R.id.detail_back_parent2);
        detailPrivary = findViewById(R.id.detail_privary);
        detailMan = findViewById(R.id.detail_man);
        detailWomen = findViewById(R.id.detail_women);
        detailCancel2 = findViewById(R.id.detail_cancel2);
        detailPrivary.setOnClickListener(this::onClick);
        detailMan.setOnClickListener(this::onClick);
        detailWomen.setOnClickListener(this::onClick);
        detailCancel2.setOnClickListener(this::onClick);
        List<UserEntity> userEntities = null;
        try {
            userEntities = DaoManager.getInstance().getDaoSession().loadAll(UserEntity.class);
            LogUtils.json(userEntities);
            int size = userEntities.size();
            detailName.setText(userEntities.get(size - 1).user_name);
            detailSex.setText(userEntities.get(size - 1).user_sex);
            user_id = userEntities.get(size - 1).user_id;

            if (userEntities.get(0).getUser_img()==null){
                Glide.with(this).load(R.drawable.pn_placeholder).into(detailHeadImg);
            }else{
                Glide.with(this)
                        .load(userEntities.get(size - 1).user_img).transform(new CenterCrop(), new CircleCrop())
                        .into(detailHeadImg);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        activityPersonalDetailsLl = (FrameLayout) findViewById(R.id.activity_personal_details_ll);


    }

    @Override
    public void inject() {
        DaggerPersonalDetailsComponent.builder().personalDetailsModules(new PersonalDetailsModules(this))
                .build().injectPersonalDetails(this);
    }

    @Override
    public void initData() {

        mPresenter = new PersonalDetailsPresenter(new PersonalDetailsModel(), this);


    }

    @Override
    protected void onStart() {
        super.onStart();
        try {
            List<UserEntity> userEntities = DaoManager.getInstance().getDaoSession().loadAll(UserEntity.class);
            LogUtils.json(userEntities);
            if (userEntities.get(0).getUser_img()==null){
                Glide.with(this).load(R.drawable.pn_placeholder)
                        .into(detailHeadImg);
            }else{
                Glide.with(this).load(userEntities.get(0).getUser_img())
                        .transform(new CenterCrop(),new CircleCrop())
                        .into(detailHeadImg);
            }

            detailName.setText(userEntities.get(0).getUser_name());
            detailSex.setText(userEntities.get(0).getUser_sex());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_img:
                detailBackParent.setVisibility(View.VISIBLE);
                Animation animation_img = AnimationUtils.loadAnimation(this, R.anim.tran);
                detailBackParent.startAnimation(animation_img);
                break;
            case R.id.rl_name:
                startPage(ModifyActivity.class);
                break;
            case R.id.rl_sex:
                detailBackParent2.setVisibility(View.VISIBLE);
                Animation animation_sex = AnimationUtils.loadAnimation(this, R.anim.tran);
                detailBackParent2.startAnimation(animation_sex);
                break;
            case R.id.detail_camera:
                openCamera();
       /*         Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                path = "/sdcard/DCIM/Camera/" + time();
                thipath = path;
                Uri uri = FileProvider.getUriForFile(this, "com.example.yaq", new File(path));
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, 102);*/
                break;
            case R.id.detail_open_photo:
              openPhoto();
              /*  Intent intent1 = new Intent();
                intent1.setAction(Intent.ACTION_PICK);
                intent1.setType("image/*");
                startActivityForResult(intent1, 111);*/
                break;
            case R.id.detail_cancel:
                detailBackParent.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_privary:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("保密");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_man:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("男");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;

            case R.id.detail_women:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("女");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_cancel2:
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.go_back1:
                try {
                    List<UserEntity> userEntities = DaoManager.getInstance().getDaoSession().loadAll(UserEntity.class);
                    String user_name = userEntities.get(0).user_name;
                    String user_sex = userEntities.get(0).getUser_sex();
                    String user_img = userEntities.get(0).getUser_img();
                    String name = detailName.getText().toString();
                    String sex = detailSex.getText().toString();

                    if (user_name==name||user_sex==sex||user_img==thipath){
                        finish();
                    }
                    try {
                        UserEntity unique = DaoManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                                .where(UserEntityDao.Properties.Id.eq(0))
                                .unique();
                        if (unique != null) {
                            if (thipath == null) {
                                unique.setUser_sex(sex);
                                unique.setUser_name(name);
                            }else{
                                unique.setUser_img(thipath);
                                unique.setUser_sex(sex);
                                unique.setUser_name(name);
                            }
                        }
                        DaoManager.getInstance().getDaoSession().update(unique);
                        mPresenter.requestUpDataUser(userEntities);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finish();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;


        }
    }
    private File file;
    private Uri uri;
    private void openCamera() {
        String name = ""+System.currentTimeMillis();
        file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath(),name+".jpg");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            //SDK版本大于10》兼容沙箱机制
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DISPLAY_NAME,name);
            values.put(MediaStore.Images.Media.RELATIVE_PATH,"Pictures");
            values.put(MediaStore.Images.Media.MIME_TYPE,"image/JPEG");
            uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            //7-9
            uri=FileProvider.getUriForFile(this,"com.example.yaq",file);
        }else{
            uri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(intent,102);
    }

    private void openPhoto(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,101);
    }


    public String time() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd_HHmmss");
        String format = simpleDateFormat.format(date);
        return "IMG" + format + ".jpg";
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode!=RESULT_OK){
            detailBackParent.setVisibility(View.INVISIBLE);
            return;
        }
        //根据requestCode区分图库或相机
        Log.i(TAG, "onActivityResult: "+requestCode);
        if (101 == requestCode){

            Cursor cursor =  getContentResolver().query(data.getData(),new String[]{MediaStore.Images.Media.DATA},
                    null,null,null);

            path = null;
            Log.i(TAG, "onActivityResult: "+path);
            while (cursor.moveToNext()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();


            Glide.with(this).load(path)
                    .transform(new CenterCrop())
                    .into(detailHeadImg);

            detailBackParent.setVisibility(View.INVISIBLE);
            upload(path);
            try {
                UserEntity  unique = DaoManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                        .where(UserEntityDao.Properties.Id.eq(0))
                        .unique();
                if (unique != null) {
                    unique.setUser_img(path);
                }
                DaoManager.getInstance().getDaoSession().update(unique);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
        if (102 == requestCode){
            path = null;
            path = file.getAbsolutePath();
            Glide.with(this).load(path)
                    .transform(new CenterCrop(),new CircleCrop())
                    .into(detailHeadImg);
            detailBackParent.setVisibility(View.INVISIBLE);
            upload(path);
            try {
                UserEntity  unique = DaoManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                        .where(UserEntityDao.Properties.Id.eq(0))
                        .unique();
                if (unique != null) {
                    unique.setUser_img(path);
                }
                DaoManager.getInstance().getDaoSession().update(unique);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    


    public void upload(String path) {
        //上传用户图片
        File file = new File(path);

        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Builder builder = new MultipartBody.Builder();

        builder.addFormDataPart("file", time(), body);

        List<MultipartBody.Part> parts = builder.build().parts();

        HttpFactory.getInstance().factory(HttpType.UPLOADTYPE)
                .getRetrofit()
                .create(Api.class)
                .uploadbean(parts)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseEntity baseEntity) {
                        Toast.makeText(PersonalDetailsActivity.this, "上传成功" , Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Toast.makeText(PersonalDetailsActivity.this, "上传失败", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
